/*
 * ---------------------------------------------------------------------------------------------------------------------------------------------------*
 * SBS Priceboard V2.0
 * Copyright (C) 2008 Unicom Vietnam JSC
 * ---------------------------------------------------------------------------------------------------------------------------------------------------* 
 * HeadURL: http://192.168.1.4/svn/priceboard/trunk/SBS_PriceboardV2/front-end/end-user/ipriceboard/src/com/unicom/priceboard/thread/SecurityThread.java
 * LastChangeBy: quanhm
 * LastChangeDate: Aug 11 2008
 */
package com.unicom.priceboard.thread;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import com.unicom.priceboard.data.OpenPriceParser;
import com.unicom.priceboard.data.hose.SecurityReader;
import com.unicom.priceboard.data.vo.HoStock;
import com.unicom.priceboard.data.vo.SecurityElement;
import com.unicom.priceboard.util.Constants;
import com.unicom.priceboard.util.DataPath;
import com.unicom.priceboard.util.ExportXML;
import com.unicom.priceboard.util.ReadFileUtil;
import com.unicom.priceboard.util.Util;

/**
 * @author ngaviet
 *
 */
public class SecurityThread implements Runnable{
	private int wait=0;
	private int curday=-1;
	private int preday=-1;
	public static boolean securityFlag=false;
	public static boolean timeWrite=false;
	private String securitySrcPath;
	public volatile static HashMap<String, HoStock> currentStockList = new HashMap<String, HoStock>();
	public volatile static HashMap<Short, String> mpStockNo = new HashMap<Short, String>();
	public static List<SecurityElement> openPrice = new ArrayList<SecurityElement>();
	public static HashMap<Short, String> lstSymbols = new HashMap<Short, String>();
	private SecurityReader parsingSecurity =new SecurityReader();
	
	private String openPricexml = DataPath.openPricexml;
	
	public SecurityThread() {
		securitySrcPath = DataPath.basePath + DataPath.securityPath;
		this.wait=Integer.parseInt(DataPath.hoseWait);
	}
	
	public void run() {		
		while(true){
			try{
				//System.out.println("Running thread....");
				if(TimerThread.CURRENT_DAY_OF_WEEK!=1 && TimerThread.CURRENT_DAY_OF_WEEK!=7) {	
					//System.out.println("In working day..");
					if(TimerThread.CURRENT_TIME>=Constants.READING_TIME_START &&TimerThread.CURRENT_TIME<Constants.READING_TIME_END) {
						//System.out.println("In working time..");
						if(ReadFileUtil.isUpToDate(Util.getCurrentDataPath(securitySrcPath)) || currentStockList.size()==0){
							//System.out.println("I'm parsing files....");
							securityFlag=false;
								curday=TimerThread.CURRENT_DAY_OF_WEEK;								
								if(curday!=preday){
									if(Integer.valueOf(MarketStatusThread.getCurrentMarketState())==3){
										timeWrite=true;
										preday=curday;
									}else if(Integer.valueOf(MarketStatusThread.getCurrentMarketState())<3||
										Integer.valueOf(MarketStatusThread.getCurrentMarketState())==Integer.valueOf(Constants.MARKET_STATE_PRE_OPEN)){
										File openpriceFile= new File(openPricexml);
										if(openpriceFile.exists()){
											openpriceFile.delete();
										}
										OpenPriceParser.mapOpenPrice.clear();
										
										//clear intra information
//										DBHoIntraStocks.clearIntraData();
									}
								}
								
								if(currentStockList.size()==0 && TimerThread.CURRENT_TIME>1020){
									OpenPriceTrigger readOpenPrice =new OpenPriceTrigger(openPricexml,wait);
									readOpenPrice.readFile();
								}
								
								parsingSecurity.parsingDatSecurity(securitySrcPath);
								securityFlag=true;
								if(timeWrite){
										if(openPrice.size()==0)
											curday=-1;
										else {
											writeXml();
											timeWrite=false;
										}										
								}
						 }//end checkmodify
					}else if(TimerThread.CURRENT_TIME<Constants.READING_TIME_START && currentStockList.size()!=0){
						//clear cache of open price the day before
						OpenPriceParser.mapOpenPrice.clear();
						openPrice.clear();
					}else if(currentStockList.size()==0){
						securityFlag=false;
						OpenPriceTrigger readOpenPrice =new OpenPriceTrigger(openPricexml,wait);
						readOpenPrice.readFile();
						parsingSecurity.parsingDatSecurity(securitySrcPath);
						securityFlag=true;
					}
				}else if(currentStockList.size()==0) {
						securityFlag=false;						
						OpenPriceTrigger readOpenPrice =new OpenPriceTrigger(openPricexml,wait);
						readOpenPrice.readFile();
						parsingSecurity.parsingDatSecurity(securitySrcPath);
						securityFlag=true;
					
				}
			}catch (Exception e) {
				//logger.debug("*****parsing Security process error :\n"+e.getMessage());
			}
			
			try {
				//logger.debug("***** parsing SECURITY.DAT Wait for " + wait + " seconds");
				Thread.sleep(1000*wait);
			} catch (Exception e) {
				//logger.debug("Exception: " + e.getMessage());
			}
//			String stockList = getStockList();
			//System.out.println("Stock list:" +stockList);
		}
		
	}
	
	/**
	 * @param symbol
	 * @return an object of HoStock
	 */
	public static HoStock getStock(String symbol) {
		return currentStockList.get(symbol);
	}
	
	/**
	 * @return a String with "," separator
	 */
	public static String getStockList() {
		StringBuffer retString = new StringBuffer("");
		List<String> sortList = new ArrayList<String>();
		sortList.addAll(currentStockList.keySet());
		Collections.sort(sortList);
		
		for(int i=0;i<sortList.size();i++){
			if(i<sortList.size()-1)
				retString.append(sortList.get(i)+",");
			else
				retString.append(sortList.get(i));
		}
		
		return retString.toString();
	}

	//Exporting OpenPrice.xml
	public  void writeXml()throws IOException {
		ExportXML.writeXml(openPricexml, openPrice);
		OpenPriceTrigger trigger =new OpenPriceTrigger(openPricexml,wait);
		trigger.readFile();
	}
}
